<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title :titleName="titleName">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="mini"
            @click="handleBack">返回
          </el-button>
          <el-button class="filter-item" type="primary"  size="mini"
            @click="handleSave">保存
          </el-button>
          <!-- <el-button class="filter-item" type="primary" icon="el-icon-check" size="mini"
            @click="handleSubmit">
            <span v-if="$route.query.type != 2">提交审批</span>
            <span v-else>提交变更审批</span>
          </el-button> -->
          <el-button class="filter-item" type="primary"  size="mini"
            @click="handleBackStep">上一步
          </el-button>
          <el-button class="filter-item" type="primary" size="mini"
            @click="handlNextStep">下一步
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!--检查项目表明细-->
      <item-title title="检测项目表明细" :borderShow="false" />
      <div v-for="(item,index) in form.stability_details" :key="index + ''" style="margin-top:30px">
        <tableTitle :table-title="item" :stability="form.stability_scheme_type" :data="data" @handlData="handlData" />
      </div>

      <div style="text-align: center;margin-top:20px">
        <el-button class="filter-item" type="primary" size="mini"
          @click="handleBackStep">返回上一步
        </el-button>
        <el-button class="filter-item" type="primary" size="mini"
          @click="handlNextStep">下一步,放样样品量信息
        </el-button>
      </div>

    </div>

    <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body
      :before-close="cancelChange" :close-on-click-modal="false" v-if="openChange">
      <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
        <el-form-item label="变更原因" prop="change_reason"
          :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
          <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancelChange">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitChange">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  stabilityEditor,
  createSave,
  updateSave,
  updateChangeSave,
  subApproval,
  submitChange
} from "@/api/stability/giveUp";
export default {
  components: {
    tableTitle: () => import("../../components/tableTitle.vue")
  },
  data() {
    return {
      titleName : '创建稳定性方案',
      dataList: [],
      tableTitle: {},
      form: {},
      data: {},
      openChange: false,
      openChangeForm: {
        id: "",
        change_reason: ""
      },
      index: 0,
      list: []
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    if (this.$route.query.id) {
      this.handlEditor();
       this.titleName = '编辑稳定性方案'
    }
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
  methods: {
    //获取编辑数据
    handlEditor() {
      stabilityEditor(this.$route.query.id).then(res => {
        if (res.code === 200) {
          if (res.data.stability_table_info !== "") {
            this.data = JSON.parse(res.data.stability_table_info) || {};
          }
          this.form = res.data;
        }
      });
    },

    handlData(list) {
      this.index++;
      this.list = this.list.concat(list);
      if (this.index === this.form.stability_details.length) {
        for (let key in this.data) {
          let index = this.list.findIndex(a => a.id == key);
          if (index == -1) {
            this.$delete(this.data, key);
          }
        }
      }
    },

    //返回
    handleBack() {
      this.$route.params.refresh = true;
      this.$router.push("/stability/giveUp");
    },

    //保存
    handleSave() {
      let stability_table_info = JSON.stringify(this.data);
      this.form.stability_table_info = stability_table_info;
      let commit = undefined,
        msg = "";
      if (this.$route.query.type == 1) {
        commit = updateSave;
        msg = "保存成功";
      } else if (this.$route.query.type == 2) {
        commit = updateChangeSave;
        msg = "方案变更保存成功";
      } else {
        commit = createSave;
        msg = "创建保存成功";
      }
      commit(this.form).then(res => {
        if (res.code == 200) {
          this.$message.success(msg);
          if (commit === updateChangeSave) {
            this.$route.params.refresh = true;
            this.$router.push("/stability/giveUp");
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    //提交审核
    handleSubmit() {
      let stability_table_info = JSON.stringify(this.data);
      this.form.stability_table_info = stability_table_info;
      if (this.form.stability_plan === "") {
        this.$message.error("稳定性试验放样信息表为空");
        return;
      }
      let aaa = this.handlTableCharm(this.data);
      if (!aaa) return;
      let bbb = JSON.parse(this.form.stability_plan) || [];
      let ccc = this.handlStableCharm(bbb);
      if (!ccc) return;
      if (this.$route.query.type == 2) {
        this.openChange = true;
      } else {
        updateSave(this.form).then(res => {
          if (res.code === 200) {
            subApproval(this.form.id).then(res => {
              if (res.code === 200) {
                this.$message.success("提交审核成功");
                this.$route.params.refresh = true;
                this.$router.push("/stability/giveUp");
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },

    //变更审核取消
    cancelChange() {
      this.openChangeForm = {
        id: "",
        change_reason: ""
      };
      this.openChange = false;
    },

    //变更审核提交
    submitChange() {
      this.$refs.openChangeForm.validate(valid => {
        if (valid) {
          updateChangeSave(this.form).then(res => {
            if (res.code === 200) {
              this.openChangeForm.id = res.data.id;
              submitChange(this.openChangeForm).then(res => {
                if (res.code === 200) {
                  this.$message.success("提交变更审批成功");
                  this.$router.push("/stability/giveUp");
                  this.cancelChange();
                } else {
                  this.$message.error(res.msg);
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },

    //返回上一步
    handleBackStep() {
      let stability_table_info = JSON.stringify(this.data);
      this.form.stability_table_info = stability_table_info;
      if (this.$route.query.id) {
        updateSave(this.form).then(res => {
          if (res.code === 200) {
            this.$router.push({
              path: "/stability/giveUp/created",
              query: { id: this.$route.query.id, type: this.$route.query.type }
            });
          }
        });
      }
    },

    //下一步
    handlNextStep() {
      //return
      let stability_table_info = JSON.stringify(this.data);
      this.form.stability_table_info = stability_table_info;
      if (this.$route.query.id) {
        updateSave(this.form).then(res => {
          if (res.code === 200) {
            this.$router.push({
              path: "/stability/giveUp/planDetail",
              query: { id: this.$route.query.id, type: this.$route.query.type }
            });
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },

    //效验检查项目表明细
    handlTableCharm(val) {
      let aa, bb, cc, dd;
      for (let key in val) {
        let dic = {};
        aa = key.split("?");
        let index = this.form.stability_details.findIndex(
          a => a.stability_sample_info.id == aa[0]
        );
        if (index !== -1) {
          bb = this.form.stability_details[index].label;
          let index1 = this.form.stability_details[
            index
          ].inspect_types.findIndex(a => a.inspect_type.id == aa[1]);
          if (index1 !== -1) {
            cc = this.form.stability_details[index].inspect_types[index1]
              .inspect_type.inspect_type_name;
            dd = bb + cc + "未勾选取样点";
          }
        }
        for (let i = 0; i < val[key].tableData.length; i++) {
          if (i != val[key].tableData.length - 1) {
            let sss = val[key].tableData[i];
            let bo = false;
            for (let obj in sss) {
              if (obj !== "name" && obj !== "num" && obj !== "boole") {
                if (typeof sss[obj] != "string") {
                  if (!dic[obj] && typeof dic[obj] != "bool") {
                    dic[obj] = false;
                  }
                  if (sss[obj]) {
                    bo = true;
                    dic[obj] = true;
                    continue;
                  }
                }
              }
            }
            if (!bo) {
              this.$message.error(dd);
              return false;
            }
          }
        }
        for (let a in dic) {
          if (!dic[a]) {
            this.$message.error(dd);
            return false;
          }
        }
      }
      return true;
    },

    //效验稳定性试验放样信息
    handlStableCharm(val) {
      for (let i = 0; i < val.length; i++) {
        let obj = val[i];
        for (let key in obj) {
          if (key.indexOf("使用倍数") != -1) {
            let sss = key.split("-");
            if (sss.length > 1 && obj[sss[1]] !== 0) {
              if (obj[key] == 0 || obj[key] == undefined) {
                this.$message.error("样品统计使用倍数不能为0");
                return false;
              }
            }
          }
        }
      }
      return true;
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
